<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../plugins/layui/css/layui.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/style.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../layuiadmin/style/admin.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/metroStyle.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/ext.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="//at.alicdn.com/t/c/font_3564966_a6tt4yhnzge.css" media="all">
    <link rel="stylesheet" href="../plugins/toastr/toastr.min.css?v=${.Config.basic.version}">
    <style>

        .layui-form-label {
            float: left;
            display: block;
            padding: 9px 15px;
            width: 60px;
            font-weight: 400;
            line-height: 20px;
            text-align: right;
        }
        .layui-form-label-sm {
            float: left;
            display: block;
            padding: 7px 5px 7px 5px;
            width: 40px;
            font-weight: 400;
            line-height: 20px;
            text-align: right;
        }
        .layui-form-item .layui-input-inline {
            float: left;
            width: 150px;
            margin-right: 10px;
        }
        .layui-form-item {
            margin-top: 5px;
            margin-bottom: 10px;
        }

        .layui-btn + .layui-btn {
            margin-left: 5px;
        }
        .layui-btn-xs {
            height: 18px;
            line-height: 18px;
            padding: 0 5px;
            font-size: 11px;
        }

        .layui-form-label-lg {
            float: left;
            display: block;
            padding: 9px 15px;
            width: 130px;
            font-weight: 400;
            line-height: 20px;
            text-align: right;
        }

        /*.layui-form-item .layui-input[readonly] {*/
        /*    background-color: #0a1434;*/
        /*    color: #a6b8d5;*/
        /*    border: none;*/
        /*    border-top-color: currentcolor;*/
        /*    border-right-color: currentcolor;*/
        /*    border-bottom-color: currentcolor;*/
        /*    border-left-color: currentcolor;*/
        /*}*/
    </style>
    <style>
        .layui-table-view .layui-table td, .layui-table-view .layui-table th {
            padding: 5px 0;
            border-top: 1px solid #404453;
            border-left: 1px solid #404453;
            border-bottom: 1px solid #404453;
            border-right: 1px solid #404453;
        }
        .layui-table-cell {
            line-height: 20px !important;
            vertical-align: middle;
            height: auto;
            overflow: visible;
            text-overflow: inherit;
            white-space: normal;
        }
        .layui-table-view .layui-table[lay-size="sm"] .layui-table-cell {
            line-height: 20px !important;
            vertical-align: middle;
            height: auto;
            overflow: visible;
            text-overflow: inherit;
            white-space: normal;
        }
    </style>
</head>

<body class="layui-layout-body">
<div class="layui-fluid">
    <div style="display: flex;">
        <div style="width: 250px;">
            <div class="layui-card tree-div">

                <div class="">
                    <div class=" " >
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>

        <div style="width: calc(100% - 250px);float: right; " >
            <div class="layui-card">
                <div class="layui-card-body">
                    <form class="layui-form" lay-filter="form" id="form" action="">
                        <div class="layui-form-item">
                            <!-- <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-sm">栏位</label>
                                <div class="layui-input-inline" style="width: 100px;">
                                    <select name="hnum" lay-verify="" lay-search="">
                                        <option value=""></option>
                                    </select>
                                </div>
                            </div>

                            <div class="layui-inline">
                                <label class="layui-form-label layui-form-label-sm">SN码</label>
                                <div class="layui-input-inline" style="width: 110px;">
                                    <input type="text" name="sn" lay-verify="" autocomplete="off" class="layui-input">
                                </div>
                            </div> -->

                            <div class="layui-inline" >
                                <label class="layui-form-label layui-form-label-sm" style="width: 60px;">日期</label>
                                <div class="layui-input-inline" style="width: 200px;">
                                    <input type="text"  class="layui-input" name="datespan" id="datespan" placeholder="">
                                </div>
                            </div>



                            <div class="layui-inline">
                                <button type="submit" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="btn_search" lay-filter="btn_search"><i class="layui-icon layui-icon-search"></i>查询</button>
                                <!-- <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm action-export layui-hide" lay-submit="btn_export" lay-filter="btn_export"><i class="layui-icon layui-icon-download-circle"></i> 导出</button> -->
                            </div>

                        </div>
                    </form>

                    <table class="layui-hide" id="table" lay-filter="table"></table>


                </div>
            </div>
        </div>
    </div>

</div>

<script src="../plugins/layui/layui.js"></script>
<script src="../plugins/jquery/jquery-3.6.0.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.core.min.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.excheck.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.exedit.js?v=${.Config.basic.version}"></script>
<script src="../plugins/jquery.slimscroll.min.js"></script>
<script src="../plugins/toastr/toastr.min.js"></script>
<script src="../plugins/moment.min.js"></script>
<script src="../js/utils.js"></script>
<script src="../js/verify.js"></script>
<script src="../js/func.js?v=${.Config.basic.version}"></script>
<script>
    var zTree=null;
    var table=null;
    var form=null;
    var Table=null;
    var lay_index=null;
    var laydate = null;

    var token = window.localStorage.getItem("token");
    var user_info=JSON.parse(window.localStorage.getItem("user_info"));
    var func_url="${.func_url}";
    var actions=[];
    var gateways=[];
    var token = window.localStorage.getItem("token");
    token = 'Bearer ' + token;
    var selectedTreeNode = null;

    var tree_setting = {
        async: {
            enable: true,
            type: "get",
            headers:{'Authorization':token},
            url: '../Api/Topo/GetAsync',
            autoParam:["id", "type"], //节点参数提交给后台,这里提交id和类型到后台
            otherParam:{"device_type":"DMXFGW"}, //静态参数
            dataFilter: filter,
        },
        view: {
            dblClickExpand: false,
            fontCss: getFont,
            nameIsHTML: true,
        },
        callback: {
            onClick: treeOnClick,
        }
    };
    function filter(treeId, parentNode, res) {
        console.info(res)
        if (!res.data) return null;
        var nodes = res.data;
        nodes=setDataIcon(nodes);
        return nodes;
    }

    layui.config({
        base: '../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index','layer','form', 'table','transfer','laydate'],function(){
        form = layui.form;
        table = layui.table;
        transfer = layui.transfer;
        laydate = layui.laydate;
        //var tomorrow = moment().add(1,"days").format('YYYY-MM-DD');
        var today = moment().format('YYYY-MM-DD');
        var yestoday = moment().add(-1,"days").format('YYYY-MM-DD');
        laydate.render({
            elem: '#datespan'
            //,type: 'datetime'
            ,range: '~'
            , theme: '#3c7cff'
            //,value: yestoday+" ~ "+today
            //,isInitValue: true
            ,done: function(value, date, endDate){
                //setTimeout(function(){load();},200);
            }
        });

        toastr.options = {
            "closeButton": false, //是否显示关闭按钮
            "debug": false, //是否使用debug模式
            "positionClass": "toast-top-center",//弹出窗的位置
            "showDuration": "300",//显示的动画时间
            "hideDuration": "1000",//消失的动画时间
            "timeOut": "2000", //展现时间
            "extendedTimeOut": "1000",//加长展示时间
            "showEasing": "swing",//显示时的动画缓冲方式
            "hideEasing": "linear",//消失时的动画缓冲方式
            "showMethod": "fadeIn",//显示时的动画方式
            "hideMethod": "fadeOut" //消失时的动画方式
        };

        form.verify({
            verify_ip:verify_ip,
            addr: function(value, item){ //value：表单的值、item：表单的DOM对象
                if(/^\d+\d+\d$/.test(value)==false){
                    return '必须是10进制数值';
                }
                if(value.length!==10){
                    return '长度必须是10';
                }
            },
            percent: function(value, item){ //value：表单的值、item：表单的DOM对象
                if(/^([0-9]{1,2}|100)$/.test(value)==false){
                    return '0-100之间的正整数';
                }
            },
        });


        $.ajax({
            type: 'GET',
            url: '../Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });



        //监听提交
        form.on('submit(btn_search)', function(data){

            //var obj={};

            var date = data.field.datespan.split(" ~ ");
            if(date.length==2){
                data.field.begin=date[0];
                data.field.end=date[1];
            }else{
                data.field.begin='';
                data.field.end='';
            }
            if(selectedTreeNode.type=="house"){
                data.field.houseid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="farm"){
                data.field.farmid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="hnum"){
                data.field.hnum_prefix = selectedTreeNode.hnum_prefix;
                data.field.houseid = selectedTreeNode.houseid;
            }
            search(data.field);
            console.info(data.field);
            return false;
        });

        form.on('submit(btn_export)', function(data){
            //toastr.warning("待开发");
            var date = data.field.datespan.split(" ~ ");
            if(date.length==2){
                data.field.begin=date[0];
                data.field.end=date[1];
            }else{
                data.field.begin='';
                data.field.end='';
            }
            if(selectedTreeNode.type=="house"){
                data.field.houseid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="farm"){
                data.field.farmid = selectedTreeNode.id;
            }else if(selectedTreeNode.type=="hnum"){
                data.field.hnum_prefix = selectedTreeNode.hnum_prefix;
                data.field.houseid = selectedTreeNode.houseid;
            }

            data.field.order = "farmname asc,housename asc,hnum asc,his_date desc";

            //data.field.begin_end=0;
            console.info(data.field);
            //return true;
            layer.load(1);
            var url="../Api/History/FeedHis/Export?"+encodeUrl(data.field);
            console.info(url);

            var xhh = new XMLHttpRequest();
            xhh.open("get", url );
            xhh.setRequestHeader("Authorization", token);
            xhh.setRequestHeader("Content-Type","application/json");
            xhh.responseType = 'blob';
            xhh.onload = function () {
                layer.closeAll('loading');
                // 请求完成
                if (this.status === 200) {
                    // 返回200
                    var blob = this.response;
                    var reader = new FileReader();
                    reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
                    reader.onload = function (e) {
                        // 转换完成，创建一个a标签用于下载
                        var a = document.createElement('a');
                        a.download = selectedTreeNode.name + "日采食记录.xlsx";
                        a.href = e.target.result;
                        $("body").append(a);    // 修复firefox中无法触发click
                        a.click();
                        $(a).remove();
                    }
                }else{
                    console.debug(this);
                }
            };
            xhh.send();

            return false;
        });

        //头工具栏事件
        table.on('toolbar(table)', function(obj){
            switch(obj.event){
                case 'addDevice':
                    onAdd();
                    break;

            };
        });

        //监听行工具事件
        table.on('tool(table)', function(obj){
            var data = obj.data;
            if(data.remark){

            }else{
                data.remark="";
            }
        });

        table.on('sort(table)', function(obj){

            table.reload('table', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    //order_field: obj.field //排序字段
                    //,order_type: obj.type //排序方式
                    order:obj.field+" "+(obj.type||"")
                }
            });
        });




        //加载tree
        loadTree();
        resizeElement();
    });

    function encodeUrl(obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    }

    


    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }

    function treeOnClick(event, treeId, treeNode) {
        selectedTreeNode=treeNode;
        resizeElement();
        console.info(selectedTreeNode);
        if(selectedTreeNode.type=="root"){
            $(".left-content").children("div").hide();
            $(".bg").show();
            toastr.info("请选择养殖场/栏舍");
            //on_view_root();
        } else if(selectedTreeNode.type=="farm"){
            $(".left-content").children("div").hide();
            $(".device_block").show();
            $("#id-title").html(selectedTreeNode.name);
            //renderSelect(selectedTreeNode.id);
            initTable();

        }else if(selectedTreeNode.type=="house"){
            $(".left-content").children("div").hide();
            $(".device_block").show();
            $("#id-title").html(selectedTreeNode.name);
            //renderSelect(selectedTreeNode.id);
            initTable();
        }else if(selectedTreeNode.type=="hnum"){
            $(".left-content").children("div").hide();
            $(".device_block").show();
            $("#id-title").html(selectedTreeNode.name);
            //renderSelect();
            initTable();
        } else{
            $(".left-content").children("div").hide();
            $(".bg").show();
        }

    }

    function treeOnExpand(event, treeId, treeNode) {
    }

    function treeOnCollapse(event, treeId, treeNode) {
        console.info(treeNode);
    }
    function deepCopy(obj) {
        if (typeof obj != 'object') {
            return obj;
        }
        var newobj = {};
        for (var attr in obj) {
            newobj[attr] = deepCopy(obj[attr]);
        }
        return newobj;
    }

    function renderSelect(){
        var obj={};
        if(selectedTreeNode.type=="house"){
            obj={houseid:selectedTreeNode.id};
        }else if(selectedTreeNode.type=="farm"){
            obj={farmid:selectedTreeNode.id};
        }else if(selectedTreeNode.type=="hnum"){
            obj={houseid:selectedTreeNode.houseid,hnum_prefix:selectedTreeNode.hnum_prefix};
        }
        $.ajax({
            type: 'GET',
            url: '../Api/Utils/Hnum',
            data: obj,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res)
                if(res.code>=0){
                    var items = res.data;
                    console.info(items)
                    //栏舍下拉
                    var html="<option value='' ></option>";
                    for(var i=0;i<items.length;i++){
                        var selectd="";
                        html+="<option "+selectd+" value=\""+items[i].hnum+"\">"+items[i].hnum+"</option>";
                    }
                    $("select[name='hnum']").html(html);
                    form.render('select');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载设备类型失败');
            }
        });

    }

    function initTable(){
        var obj=form.val("form");
        console.info(obj);
        if(selectedTreeNode.type=="house"){
            obj.houseid = selectedTreeNode.id;
        }else if(selectedTreeNode.type=="farm"){
            obj.farmid = selectedTreeNode.id;
        }else if(selectedTreeNode.type=="hnum"){
            obj.hnum_prefix = selectedTreeNode.hnum_prefix;
            obj.houseid = selectedTreeNode.houseid;
        }
        
        var date = obj.datespan.split(" ~ ");
        if(date.length==2){
            obj.begin=date[0];
            obj.end=date[1];
        }else{
            obj.begin='';
            obj.end='';
        }
        //obj.begin_end=0;
        obj.order = "act_time desc";

        Table = table.render({
            elem: '#table'

            ,url: "../Api/Log/DeliverLog"
            ,height: 'full-80'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: obj
            ,page: {
                limit:300,
                limits:[10, 20, 30, 40, 50,100,200,300,400],
                theme: '#3c7cff'
            }
            /*,initSort: {
                field: 'hnum' //排序字段，对应 cols 设定的各字段名
                ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
            }*/
            ,limit:30
            //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: ''
            ,even:true
            ,size: 'sm' //小尺寸的表格
            ,skin: 'nob' //无框风格
            ,cols: [[
                //{type: 'checkbox', fixed: 'left'}
                //,fixed: 'left'
                {type: 'numbers',title:'序号'}
                ,{field:'farmname', title:'场区',minWidth:150, sort: false}
                ,{field:'housename', title:'栏舍单元',minWidth:120, sort: true}
                ,{field:'addr', title:'终端设备SN',width:120, sort: true}
                ,{field:'sn', title:'拉料设备SN',width:120, sort: true}
                
                ,{field:'reason', title:'触发条件', sort: false}//
                ,{field:'act_time', title:'拉料时间',width:160, sort: true}
                ,{field:'act_res', title:'操作结果',width:110, sort: true,templet: function(d){
                        return d.act_res==="ok"?"<i class=\"layui-icon layui-icon-ok-circle layui-text-green \"></i>":"<span class=\" layui-text-orange \">"+d.act_res+"</span>";
                    }}
                

            ]]
            ,done: function(res, curr, count){
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
                // var that = this.elem.next();
                // res.data.forEach(function (item, index) {
                //     //console.log(item.empName);item表示每列显示的数据
                //     if (index % 2 != 0) {
                //         var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", "#0a1434");
                //     } else {
                //         var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", "#00092b");
                //     }
                // });
            }
        });

        //监听行工具事件
        table.on('tool(table)', function(obj){
            var data = obj.data;
            console.info(obj)
            if(obj.event === 'paraLog'){
                onParaOpHisReadonly(data)
            }
        });
    }


    //参数操作历史
    function onParaOpHisReadonly(item){
        var idx = layer.open({
            area:['95%','85%'],
            type: 2,
            shadeClose: true,
            shade: 0.8,
            title: item.farmname+" "+item.housename+" "+item.feed_plan_name,
            maxmin: false, //开启最大化最小化按钮
            content: '../Device/ParaOpHisReadonly?'+$.param(item)
        });
    }

    function search(params) {
        Table.reload({
            where: params
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    }

    function loadTree() {
        //layer.load(1);
        /*$.ajax({
            type: 'GET',
            url: '../Api/Topo',
            data: {show_hnum:0},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                //var data=data.data;
                var nodes=setDataIcon(data.data);
                console.info(nodes);
                zTree = $.fn.zTree.init($("#treeDemo"), tree_setting, nodes);

                var nodes = zTree.getNodesByParam("type", "farm", null);
                if(nodes.length>0){
                    const node = nodes[0];
                    console.info(node);
                    zTree.selectNode(node);
                    setTimeout(function(){zTree.setting.callback.onClick(null,null,node);},200);


                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
        });
        */
        zTree = $.fn.zTree.init($("#treeDemo"), tree_setting);
    }


    //设置图标
    function setDataIcon(data){

        for(let i=0; i<data.length; i++){
            var node=data[i];

            node['font']={'color':'#333'};
            if(node.type=='group'){
                //node.name = "";
                node["icon"]="../plugins/zTree/css/metroStyle/img/net.png";
                //node.isParent=true;
                node.open = true;
            }
            else if(node.type=='area'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/area.png";
                //node.isParent=true;
                node.open = true;
            }
            else if(node.type=='farm'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/location.png";
                node.isParent=true;
            }else if(node.type=='house'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/house.png";
                node.isParent=false;
                if(node.device_online)
                {
                    node['font']={'color':'#3c7cff'};
                }else{
                    node['font']={'color':'#A3A8B6'};
                }
                //node['font']={'color':'#4958b9','font-weight':"bold"};
            }
            else if(node.type=='hnum') {
                node["icon"] = "../plugins/zTree/css/metroStyle/img/farm.png";
                //node.isParent=true;
                //node.open=true;
            }
            if(node['children']){
                var data1=node.children;
                setDataIcon(data1);
            }
        }
        return data;
    }

    $(window).resize(function () {
        //console.info('resize')
        resizeElement();
    });
    function resizeElement() {
        //$('.tree-div').height($(window).height()-60);
        $(".tree-div").slimScroll({
            height: $(window).height()-10,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });
    }

</script>
<script src="../js/check_screen.js?v=${.Config.basic.version}"></script>

</body>


</html>